import 'dart:convert';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:cave_flutter/db_manager/bean/whl_product_bean.dart';
import 'package:cave_flutter/model/base_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_home/soul_interaction/soul_interaction_view.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';
import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../../model/user_model.dart';
import 'map_search/map_search_view.dart';

class WhlHomeLogic extends GetxController {
  int selectedIndex = 10;
  List<BaseModel> tabList = [
    BaseModel(title: '蜜语'),
    BaseModel(title: '附近'),
    BaseModel(title: '排行榜'),
  ];
  String latitude = '';
  String longitude = '';
  String locationDescription = '';
  int selectedTabIndex = 1;
  List<WhlProductBean> productList = [];
  SwiperController swiperController = SwiperController();
  EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  Map<String, dynamic> nearbyQueryParams = {};

  int page = 1;
  int size = 10;

  List<UserModel> nearbyList = [];

  late AMapFlutterLocation flutterLocation;

  @override
  void onInit() {
    super.onInit();
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    flutterLocation = AMapFlutterLocation();
    // flutterLocation.setLocationOption(AMapLocationOption(
    //     onceLocation: true,
    //     geoLanguage: GeoLanguage.ZH,
    //     locationMode: AMapLocationMode.Hight_Accuracy,
    //     locationInterval:2000,
    //     pausesLocationUpdatesAutomatically:false,
    //     desiredAccuracy:DesiredAccuracy.Best
    // ));
    WhlPermissionUtil.reqLocationWhenInUsePermission(onSuccessAction: () {
      flutterLocation.startLocation();
    });
    flutterLocation.onLocationChanged().listen((event) {
      if (event != null) {
        latitude = event['latitude'].toString();
        longitude = event['longitude'].toString();
        locationDescription = event['description'].toString();
        saveUserLocation(event);
      }
      flutterLocation.stopLocation();
    });
    flutterLocation.startLocation();
    getNearbyData(isRefresh: true);
  }

  @override
  onClose() {
    super.onClose();
    flutterLocation.stopLocation();
    flutterLocation.destroy();
  }

  setNearbyQueryParams(Map<String, dynamic> params) {
    nearbyQueryParams = params;
    getNearbyData(isRefresh: true);
  }

  saveUserLocation(Map<String, dynamic> map) {
    //经纬度转换为double类型
    map["latitude"] = map["latitude"] is String
        ? double.tryParse(map["latitude"])
        : map['latitude'];
    map["longitude"] = map['longitude'] is String
        ? double.tryParse(map["longitude"])
        : map['longitude'];
    // nearbyQueryParams['latitude'] = map["latitude"];
    // nearbyQueryParams['longitude'] = map["longitude"];
    WhlApi.saveUserLocation.post(map, hideMsg: true).then((value) {
      // if (value.isSuccess()) {
      //   MyToast.show("定位保存成功");
      // } else {
      //   MyToast.show("定位保存失败");
      // }
    });
  }

  getNearbyData({bool isRefresh = false}) {
    if (isRefresh) {
      page = 1;
    } else {
      page++;
    }
    nearbyQueryParams['cursor'] = page;
    nearbyQueryParams['size'] = size;

    WhlApi.getNearbyPeople.get(nearbyQueryParams).then((value) {
      if (value.isSuccess()) {
        List records = value.data["list"] ?? [];
        List<UserModel> modelList =
            records.map((e) => UserModel.fromJson(e)).toList();
        if (isRefresh) {
          nearbyList = modelList;
          refreshController.finishRefresh();
          refreshController.resetFooter();
        } else {
          nearbyList.addAll(modelList);
          refreshController.finishLoad();
        }
        if (modelList.length < size) {
          refreshController.finishLoad(IndicatorResult.noMore);
        }
        update();
      } else {
        page--;
        refreshController.finishRefresh();
        refreshController.finishLoad();
        update();
      }
    });
  }

  onGetProductList() async {
    // List<WhlProductBean>? result = await WhlDBUtils().productDao.findAllProducts();
    // if (result != null && result.isNotEmpty) {
    //   result.shuffle();
    //   productList = result;
    //   update();
    //   return;
    // }
    // BotToast.showLoading();
    String json = await rootBundle.loadString("assets/json/data.json");
    List dataMap = jsonDecode(json);
    Map<String, dynamic> params = {
      "category": "Popular",
      "isPageMode": true,
      "isRemoteImageUrl": true,
      "limit": 20,
      "page": 1,
      "tag": "All",
    };
    // ResponseData responseData = await WhlApi.getWall.post(params);
    // if (responseData.isSuccess()) {
    //   List list = responseData.data;
    //   List<WhlProductBean> modelList = list.map((e) => WhlProductBean.fromJson(e)).toList();
    //   List<WhlProductBean> tempList = [];
    //   for (var element in dataMap) {
    //     int index = dataMap.indexOf(element);
    //     if (index >= modelList.length) {
    //       break;
    //     }
    //     WhlProductBean model = modelList[index];
    //     List productList = element['product'];
    //     for (var element in productList) {
    //       model.title = element['title'];
    //       model.describe = element['describe'];
    //       model.type = element['type'];
    //       model.cover = element['cover'];
    //       model.details = (element['details'] as List).map((e) => e.toString()).toList();
    //       model.likeNum = Random().nextInt(20);
    //       model.isLike = false;
    //       model.isFollowed = false;
    //       model.followNum = Random().nextInt(20);
    //       tempList.add(model);
    //       // WhlDBUtils().productDao.insertProduct(model);
    //     }
    //   }
    //   productList = tempList;
    //   update();
    // }
    // BotToast.closeAllLoading();
  }

  doClickFollow(WhlProductBean model) {
    model.isFollowed = true;
    model.followNum = (model.followNum ?? 0) + 1;
    update();
    WhlDBUtils().productDao.updateProduct(model);
    Map<String, dynamic> params = {
      'followUserId': model.userId,
    };
    // WhlApi.addFriend.post(params);
  }

  doClickCancelFollow(WhlProductBean model) {
    model.isFollowed = false;
    model.followNum = (model.followNum ?? 0) - 1;
    update();
    WhlDBUtils().productDao.updateProduct(model);
    Map<String, dynamic> params = {
      'followUserId': model.userId,
    };
    // WhlApi.removeFriend.post(params);
  }

  onRefresh() async {
    getNearbyData(isRefresh: true);
  }

  doClickShare() {
    Get.toNamed(Routes.publish);
  }

  doClickTopBanner(int index) {
    if (index == 0) {
      Get.toNamed(Routes.heartbeatRadio);
    } else if (index == 1) {
      Get.toNamed(Routes.caveMutualPage);
    } else if (index == 2) {
      Get.toNamed(Routes.caveFindPage);
    }
  }

  void goMapSearchPage() {
    Get.to(
      () => Map_searchPage(
        latitude: this.latitude,
        longitude: this.longitude,
      ),
    )?.then((value) {
      print(value);
    });
  }
}
